为什么java.util.HashSet没有get(Object o)方法?

您所在的位置:网站首页 java set get 为什么java.util.HashSet没有get(Object o)方法?

为什么java.util.HashSet没有get(Object o)方法?

#为什么java.util.HashSet没有get(Object o)方法?| 来源: 网络整理| 查看: 265

我见过其他关于基于索引值从Set获取对象的问题,我理解为什么这是不可能的,但我没有找到一个很好的解释为什么get by object是不允许的,所以我想我会问。

HashSet是由HashMap支持的,所以从它获取一个对象应该是相当简单的。现在看来,我必须遍历HashSet中的每一项并测试相等性,这似乎是不必要的。

我可以只使用Map,但我不需要键:值对,我只需要一个Set。

例如,假设我有Foo.java

package example; import java.io.Serializable; public class Foo implements Serializable { String _id; String _description; public Foo(String id){ this._id = id } public void setDescription(String description){ this._description = description; } public String getDescription(){ return this._description; } public boolean equals(Object obj) { //equals code, checks if id's are equal } public int hashCode() { //hash code calculation } }

和Example.java

package example; import java.util.HashSet; public class Example { public static void main(String[] args){ HashSet set = new HashSet(); Foo foo1 = new Foo("1"); foo1.setDescription("Number 1"); set.add(foo1); set.add(new Foo("2")); //I want to get the object stored in the Set, so I construct a object that is 'equal' to the one I want. Foo theFoo = set.get(new Foo("1")); //Is there a reason this is not allowed? System.out.println(theFoo.getDescription); //Should print Number 1 } }

这是因为equals方法的目的是测试“绝对”相等而不是“逻辑”相等(在这种情况下,contains(Object o)就足够了)?



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3